"""
使用dict.txt文件
编写一个函数,参数传入一个单词,函数的返回值是这个单词的所在行内容
如果单词不存在,返回None

tips:
    1.文件每个单词占一行
    2.单词与解释之间有空格
    3.单词按照从小到大排列
"""
from time import time

file_path = "../dict.txt"
file_dict = open(file_path, 'r')

list_dict = file_dict.readlines()

file_dict.close()


# 时间
def execute_time(func):
    def wrapper(*args, **kwargs):
        start_time = time()
        func(*args, **kwargs)
        end_time = time()

        print(f"{end_time - start_time}s")

    return wrapper


# 1.
@execute_time
def func01():
    def binary_search(iterable, *, key, target):
        if len(iterable) == 0:
            return None
        mid = len(iterable) // 2
        if target == key(iterable[mid]):
            return iterable[mid]
        elif target < key(iterable[mid]):
            del iterable[mid + 1:len(iterable)]
            return binary_search(iterable[0:mid], key=lambda item: item.split(" ")[0], target=target)
        elif target > key(iterable[mid]):
            del iterable[0:mid]
            return binary_search(iterable[mid + 1:len(iterable)], key=lambda item: item.split(" ")[0], target=target)

    print(binary_search(list_dict, key=lambda item: item.split(" ")[0], target="a"))


func01()


# 2.
@execute_time
def func02():
    def binary_search(iterable, *, key, target, l, r):
        if l > r:
            return None
        mid = (l + r) // 2
        if target == key(iterable[mid]):
            return iterable[mid]
        elif target < key(iterable[mid]):
            return binary_search(iterable, key=lambda item: item.split(" ")[0], target=target, l=l, r=mid - 1)
        elif target > key(iterable[mid]):
            return binary_search(iterable, key=lambda item: item.split(" ")[0], target=target, l=mid + 1, r=r)

    print(binary_search(list_dict, key=lambda item: item.split(" ")[0], target="abbey", l=0, r=len(list_dict)))


func02()


# 3.
@execute_time
def binary_search(iterable, *, key, target):
    def search(*, l=0, r=len(iterable) - 1):
        if l > r:
            return None
        mid = (l + r) // 2
        if target == key(iterable[mid]):
            return iterable[mid]
        elif target < key(iterable[mid]):
            return search(l=l, r=mid - 1)
        elif target > key(iterable[mid]):
            return search(l=mid + 1, r=r)

    return search()


print(binary_search(list_dict, key=lambda item: item.split(" ")[0], target="abbey"))


# 4.
@execute_time
def func():
    target = "abbey"
    for line in file_dict:
        if target == line.split(" ")[0]:
            print(line)
            break


target = "abbey"
for line in file_dict:
    if target > line.split(" ")[0]:
        print(None)
        break
    elif target == line.split(" ")[0]:
        print(line)
        break
